<template>
  <div>
    <div class="pad-b-15">
      <el-button type="primary" @click="doBatchAutoWarehouse">批量重新分仓</el-button>
      <el-button type="primary" @click="doBatchSelectWarehouse">批量指定发货仓</el-button>
    </div>
    <!--顶部搜索 -->
    <div class="top-operate-default pad-l-20">
      <div class="inline-flex">
        <el-select v-model="textCol" class="width-120">
          <el-option label="全部" value=""></el-option>
          <el-option label="订单号" value="projectOrderNo"></el-option>
          <el-option label="子订单号" value="orderNo"></el-option>
          <el-option label="平台订单号" value="externalOrderNo"></el-option>
          <el-option label="来源订单号" value="sellApartOrderNo"></el-option>
          <el-option label="来源企业" value="supplyAllianceEnterpriseName"></el-option>
          <el-option label="收货人" value="customerNickname"></el-option>
          <el-option label="收货人手机" value="customerPhone"></el-option>
          <el-option label="商品名称" value="goodsTitle"></el-option>
        </el-select>
        <el-input v-model="textValue" placeholder="请输入内容" class="width-200"></el-input>
      </div>
      <div class="inline-flex">
        <el-select value="1" class="mar-l-10 width-120">
          <el-option label="失败原因" value="1"></el-option>
        </el-select>
        <el-input v-model="defaultQuery.separateFailMsg" placeholder="请输入失败原因" class="width-200"></el-input>
      </div>
      <el-select v-model="defaultQuery.orderType" placeholder="订单类型" clearable class="mar-l-10" style="width: 150px">
        <el-option v-for="(val, key) in dict.orderType" :key="key" :label="val" :value="key"></el-option>
      </el-select>
      <el-select v-model="defaultQuery.isSupplyAllianceOrder" placeholder="订单来源" clearable class="mar-l-10 cus-select">
        <el-option label="全部" value=""></el-option>
        <el-option label="企业订单" value="0"></el-option>
        <el-option label="供货联盟订单" value="1"></el-option>
      </el-select>
      <div class="inline-flex">
        <el-select v-model="defaultQuery.crossBorderOrderType" placeholder="全部跨境订单类型" clearable class="mar-l-10"
          style="width: 150px">
          <el-option v-for="(val, key) in dict.crossBorderOrderType" :key="key" :label="val" :value="key"></el-option>
        </el-select>
      </div>
      <el-button-group class="mar-l-20">
        <el-button type="primary" @click="doSearch">查询</el-button>
        <el-button @click="doResetSearch">重置</el-button>
      </el-button-group>
    </div>
    <!-- 内容列表 -->
    <div class="table-container mar-t-15">
      <el-table :data="dataList" @selection-change="handleSelectionChange" v-loading="listLoading"
        element-loading-text="加载中">
        <el-table-column width="50px" type="selection"></el-table-column>
        <el-table-column width="260px" label="订单信息">
          <template slot-scope="scope">
            <div class="flex v-align-c cursor-p" @click="doLinkDetail(scope.row)">
              <label v-if="scope.row.goodsImageUrl"><img :src="scope.row.goodsImageUrl"
                  class="t-goods-pic cursor-p"></label>
              <div class="font-14 pad-l-10 line-2 goods-title">
                <span>{{ scope.row.goodsTitle }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column min-width="280px" label="订单号">
          <template slot-scope="scope">
            <div>{{ scope.row.projectOrder.orderNo }}</div>
            <div>子订单号：{{ scope.row.orderNo }}</div>
            <div v-if="scope.row.projectOrder.crossBorderOrderType === 2" style="color: #3a8ee6;">（跨境保税订单）</div>
          </template>
        </el-table-column>
        <el-table-column width="140px" label="收货人">
          <template slot-scope="scope">
            <div v-if="scope.row.projectOrder.customerNickname">
              <div>{{ scope.row.projectOrder.customerNickname }}</div>
              <div>{{ scope.row.projectOrder.customerPhone }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column min-width="150px" label="订单类型" align="center">
          <template slot-scope="scope">
            <div>{{ dict.orderType[scope.row.projectOrder.orderType] }}</div>
          </template>
        </el-table-column>
        <el-table-column width="200px" label="订单来源" align="center" prop="sellApartOrderNo">
          <template slot-scope="scope">
            <span v-if="scope.row.sellApartOrderNo != null && scope.row.sellApartOrderNo != ''">
              <span>供货联盟订单</span>
              <div>{{scope.row.supplyAllianceEnterpriseName}}</div>
            </span>
            <span v-else>企业订单</span>
          </template>
        </el-table-column>
        <el-table-column width="90px" label="数量" prop="goodsNum" align="center">
        </el-table-column>
        <el-table-column width="140px" label="订单金额" prop="orderPrice">
          <template slot-scope="scope">
            <div>商品：￥{{ scope.row.orderPrice }}</div>
            <div>运费：￥{{ scope.row.freight }}</div>
            <div
              v-if="scope.row.projectOrder.crossBorderOrderType === 2 && scope.row.projectOrder.comprehensiveTaxAmount">
              税费：￥{{ scope.row.projectOrder.comprehensiveTaxAmount }}</div>
          </template>
        </el-table-column>
        <el-table-column width="160px" label="生成时间" prop="createTime" align="center">
        </el-table-column>
        <el-table-column width="240px" label="分仓失败原因" prop="separateFailMsg" align="left">
        </el-table-column>
        <el-table-column min-width="150px" label="仓库报关状态" prop="customsStatus" align="center">
          <template slot-scope="scope">
            {{dict.warehouseCustomsStatus[scope.row.projectOrder.warehouseCustomsStatus]}}
          </template>
        </el-table-column>
        <el-table-column min-width="150px" label="支付单报关状态" prop="customsStatus" align="center">
          <template slot-scope="scope">
            {{dict.paymentOrderCustomsStatus[scope.row.projectOrder.paymentOrderCustomsStatus]}}
          </template>
        </el-table-column>
        <el-table-column min-width="120px" label="操作" align="right" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="medium" class="table-btn" @click="doLinkDetail(scope.row)">查看详情</el-button>
            <el-button type="text" size="medium" class="table-btn" v-if="scope.row.canResetWarehouse == 1"
              @click="doAutoWarehouse(scope.row)">重新分仓</el-button>
            <el-button type="text" size="medium" class="table-btn"
              v-if="scope.row.canResetWarehouse == 1 && scope.row.projectOrder.crossBorderOrderType !== 2"
              @click="doSelectWarehouse(scope.row)">指定发货仓</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 列表分页 -->
    <div class="pagination">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="searchListQuery.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="searchListQuery.size"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog width="600px" v-el-drag-dialog title="仓库选择" :visible.sync="warehouseVisible">
      <el-form ref="divideForm" :model="divideForm" :rules="rules" label-position="right" label-width="100px"
        style='width: 500px; margin-left:50px;'>
        <el-form-item label="收货仓：">
          <el-select v-model="divideForm.warehouseId" placeholder="仓库" clearable class="pad-l-10">
            <el-option v-for="(item, index) in warehouseList" :key="index" :label="item.warehouseName"
              :value="item.warehouseId">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="warehouseVisible = false">取消</el-button>
        <el-button type="primary" @click="doConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getDictByGroupName
  } from '@/api/common/common'
  import {
    listWarehouseInfo
  } from '@/api/warehouse/warehouseInfo'
  import {
    pageApartOrder,
    doResetWarehouse,
    doSetWarehouse,
    batchResetWarehouse,
    batchSetWarehouse
  } from '@/api/goods/apartOrder'
  import elDragDialog from '@/directive/el-dragDialog'
  export default {
    directives: {
      elDragDialog
    },
    components: {},
    data() {
      return {
        // 文本model
        textCol: '',
        textValue: '',
        // 查询条件
        searchListQuery: {},
        // 默认条件
        defaultQuery: {
          enterpriseId: '',
          supplierId: '',
          currentPage: 1,
          size: 10,
          waitSeparateWarehouseFlag: 1,
          orderStatus: 1,
          source: '',
          orderType: '',
          crossBorderOrderType: ''
        },
        // 数据字典
        dict: {
          orderType: {},
          crossBorderOrderType: {},
          customsStatus: {}
        },
        // 分仓表单
        divideForm: {
          apartOrderId: '',
          apartOrderIds: [],
          warehouseId: ''
        },
        // 表单规则
        rules: {
          warehouseId: [{
            required: true,
            message: '请选择仓库',
            trigger: 'blur'
          }]
        },
        // 仓库集合
        warehouseList: [],
        // 仓库选择visible
        warehouseVisible: false,
        total: 0,
        listLoading: false,
        dataList: [],
        multipleSelection: []
      }
    },
    created() {
      this.searchListQuery = {
        ...this.defaultQuery
      }
      // 获取数据字典
      getDictByGroupName('ProjectOrderDTO').then(response => {
        Object.assign(this.dict, response.data)
      })
      // 获取仓库列表
      const form = {
        enterpriseId: this.getEnterpriseId(),
        supplierId: this.getSupplierId(),
        warehouseSource: this.getSupplierId() ? 2 : 1,
        status: 1
      }
      listWarehouseInfo(form).then((response) => {
        this.warehouseList = response.data
      })
      this.initList()
    },
    methods: {
      // 初始化
      initList() {
        this.listLoading = true
        const size = this.searchListQuery.size
        const currentPage = this.searchListQuery.currentPage
        const crossBorderOrderType = this.defaultQuery.crossBorderOrderType
        this.searchListQuery = {
          ...this.defaultQuery
        }
        this.searchListQuery.size = size
        this.searchListQuery.currentPage = currentPage
        this.searchListQuery.crossBorderOrderType = crossBorderOrderType
        this.searchListQuery[this.textCol] = this.textValue
        this.searchListQuery.enterpriseId = this.getEnterpriseId()
        this.searchListQuery.supplierId = this.getSupplierId()
        pageApartOrder(this.searchListQuery).then(response => {
          this.listLoading = false
          if (response.isError) return
          this.total = response.data.total
          this.dataList = response.data.records
        })
      },
      // 查询事件
      doSearch() {
        this.searchListQuery.currentPage = 1
        this.initList()
      },
      // 重置事件
      doResetSearch() {
        const originData = this.$options.data()
        this.textCol = originData.textCol
        this.textValue = originData.textValue
        this.defaultQuery = originData.defaultQuery
        this.doSearch()
      },
      // 查看详情事件
      doLinkDetail(row) {
        this.$router.push({
          path: '/order/apart-detail',
          query: {
            apartOrderId: row.apartOrderId
          }
        })
      },
      // 重新分仓事件
      doAutoWarehouse(row) {
        this.listLoading = true
        doResetWarehouse(row.apartOrderId).then((response) => {
          if (response.isError) {
            if (response.code === 102) {
              this.$message({
                type: 'error',
                message: response.msg
              })
            }
          } else {
            this.$message({
              type: 'success',
              message: '保存成功'
            })
          }
          this.initList()
        })
      },
      // 批量重新分仓事件
      doBatchAutoWarehouse() {
        if (this.multipleSelection.length === 0) {
          this.$message({
            type: 'error',
            message: '请选择订单'
          })
          return
        }
        var crossBorderOrderType = []
        var apartOrderIds = []
        this.multipleSelection.forEach(item => {
          crossBorderOrderType.push(item.projectOrder.crossBorderOrderType)
          apartOrderIds.push(item.apartOrderId)
        })
        if (crossBorderOrderType.length > 1) {
          this.msgError('普通和跨境订单，不能同时批量分仓!')
          return
        }
        this.listLoading = true
        batchResetWarehouse(apartOrderIds).then(response => {
          if (response.isError) {
            this.listLoading = false
            return
          }
          const data = response.data
          const msg = '共处理' + data.total + '笔，成功' + data.success + '笔，失败' + data.failure + '笔'
          const type = data.failure > 0 ? 'error' : 'success'
          this.$message({
            type: type,
            message: msg
          })
          this.initList()
        })
      },
      // 指定分仓事件
      doSelectWarehouse(row) {
        const originData = this.$options.data()
        this.divideForm = originData.divideForm
        this.divideForm.apartOrderId = row.apartOrderId
        this.warehouseVisible = true
      },
      // 批量指定分仓事件
      doBatchSelectWarehouse() {
        if (this.multipleSelection.length === 0) {
          this.$message({
            type: 'error',
            message: '请选择订单'
          })
          return
        }
        var crossBorderOrderType = []
        var apartOrderIds = []
        this.multipleSelection.forEach(item => {
          crossBorderOrderType.push(item.projectOrder.crossBorderOrderType)
          apartOrderIds.push(item.apartOrderId)
        })
        if (crossBorderOrderType.length > 1 || crossBorderOrderType[0] === 2) {
          if (this.multipleSelection.length > 1) {
            this.msgError('选择订单包含跨境订单，不能批量指定发货仓!')
          } else {
            this.msgError('选择的订单是跨境订单，不能批量指定发货仓!')
          }
          return
        }
        const originData = this.$options.data()
        this.divideForm = originData.divideForm
        this.divideForm.apartOrderIds = apartOrderIds
        this.warehouseVisible = true
      },
      // 分仓确定事件
      doConfirm() {
        this.$refs['divideForm'].validate((valid) => {
          if (valid) {
            this.listLoading = true
            if (this.divideForm.apartOrderIds.length > 0) {
              batchSetWarehouse(this.divideForm.apartOrderIds, this.divideForm.warehouseId).then(response => {
                if (response.isError) {
                  this.listLoading = false
                  return
                }
                const data = response.data
                const msg = '共处理' + data.total + '笔，成功' + data.success + '笔，失败' + data.failure + '笔'
                const type = data.failure > 0 ? 'error' : 'success'
                this.$message({
                  type: type,
                  message: msg
                })
                this.initList()
              })
            } else {
              doSetWarehouse(this.divideForm.apartOrderId, this.divideForm.warehouseId).then((response) => {
                if (response.isError) {
                  if (response.code === 102) {
                    this.$message({
                      type: 'error',
                      message: response.msg
                    })
                  }
                } else {
                  this.$message({
                    type: 'success',
                    message: '保存成功'
                  })
                }
                this.warehouseVisible = false
                this.initList()
              })
            }
          }
        })
      },
      // 勾选事件
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      // 更改当前页数
      handleCurrentChange(val) {
        this.searchListQuery.currentPage = val
        this.initList()
      },
      // 更改当前页面大小
      handleSizeChange(val) {
        this.searchListQuery.size = val
        this.initList()
      }
    }
  }
</script>

<style lang="less" scoped>

</style>
